<?php

class User_Ui{
	
	private $user;
	
	
	public function __construct($user) {
		$this->user = $user;	
	}
	
	public function getUserStats(){
		$html =<<<EOT
			<section class="stats">
				<h1>Vos statistiques de participation</h1>
				{$this->participationChart()}
			</section>
			<section class="stats">
				<h1>Vos statistiques d évaluation</h1>
				{$this->evalChart()}
			</section>
EOT;
		
		return $html;	
		
	}
	
	private function participationChart(){
		//$seniority = User_Bd::getSeniority($this->user->getIdUser());
		$seniority = $this->getSeniority();
		if ($seniority < 1)
			return "<p>Vos statistiques sont actuellement indisponibles. Veuillez attendre au moins 24h si vous venez de vous inscrire.</p>";
		//$seniority = 5;
		$alt="";
		$chart = "https://chart.googleapis.com/chart?chs=300x150&amp;chof=png&amp;chf=bg,s,E6E6E6&amp;chco=7EB7BF&amp;chbh=a&amp;";
		$cht="";
		$chd = "";
		$averageRating=0; 
		if (($seniority/7)>=12){
			$resultByW = $this->getStatsHistory(WEEK,12);
			$alt="Nombres d'évaluations par semaine durant ces 3 derniers mois";
			//var_dump($resultByW);
			$chxlX2 = "|".date('M',mktime(0, 0, 0, date("m")-2, date("d"),   date("Y")))."|".date('M',mktime(0, 0, 0, date("m")-1, date("d"),   date("Y")))."|".date('M');
			$chxlX1 = "|";
			$currentWeekofMonth = (int)ceil((date("d") - date("w") - 1) / 7) + 1;
			$max = 0;
			$totalRatingPeriod=0;
			$averageRatingUnit = "semaine";
			foreach($resultByW as $elt){
				$totalRatingPeriod+=$elt['nb_rating'];
				$chd.=$elt['nb_rating'];
				$chd.=",";
				$chxlX1.=$elt['n_t'];
				$chxlX1.="|";
				if ($elt['nb_rating'] > $max)
					$max = $elt['nb_rating'];
			}
			for($i=1;$i<=3;$i++){
				$chxp[$i]=(int)($i/3*100-(($currentWeekofMonth-1)*100/12));
			}
			$chd = substr($chd,0,-1);
			$chart .= "cht=lc&amp;chd=t:{$chd}&amp;chxt=x,x,y&amp;chxl=0:{$chxlX1}1:{$chxlX2}&amp;chxp=1,{$chxp[1]},{$chxp[2]},{$chxp[3]}&chds=0,{$max}&amp;chxr=2,0,{$max}";
			$averageRating = round($totalRatingPeriod/sizeof($resultByW));
		}
		else {
			if (($seniority/7)>=3){
				$resultByW = $this->getStatsHistory(WEEK,3);
				$alt="Nombres d'évaluations par semaine durant ces 3 dernières semaines";
				//var_dump($resultByW);
				$max = 0;
				$totalRatingPeriod=0;
				$averageRatingUnit = "semaine";
				//print_r($resultByW);
				foreach($resultByW as $elt){
					$totalRatingPeriod+=$elt['nb_rating'];
					$chd.=$elt['nb_rating'];
					$chd.=",";	
					if ($elt['nb_rating'] > $max)
						$max = $elt['nb_rating'];
				}
				$chd = substr($chd,0,-1);
				$chart .= "cht=bvs&amp;chd=t:{$chd}&amp;chxt=x,y&amp;chxl=0:|||Cette%20semaine&amp;chds=0,{$max}&amp;chxr=1,0,{$max}";
				$averageRating = round($totalRatingPeriod/sizeof($resultByW));
			}
			else {
				$resultByD = $this->getStatsHistory(DAY,7);
				$alt="Nombres d'évaluations par jour sur les 7 derniers jours";
				$chxlX1 = "|";
				$max = 0;
				$totalRatingPeriod = 0;
				$averageRatingUnit = "jour";
				foreach($resultByD as $k=>$v){
					$totalRatingPeriod+=$v;
					$chd.=$v;
					$chd.=",";
					$chxlX1 .= date('D d',strtotime($k));
					$chxlX1 .= "|";
					if ($v > $max)
						$max = $v; 	
				}
				$chd = substr($chd,0,-1);
				$chxlX1 = substr($chxlX1,0,-1);
				$chart .= "cht=bvs&amp;chd=t:{$chd}&amp;chxt=x,y&amp;chxl=0:{$chxlX1}&amp;&chds=0,{$max}&amp;chxr=1,0,{$max}";
				$averageRating = round($totalRatingPeriod/sizeof($resultByD));	
			}
		}

		$chartImg = "<figure><figcaption>{$alt} :</figcaption> <img src=\"{$chart}\" alt=\"{$alt}\"/></figure> ";
		
		$totalRating = User_Bd::getRatingCount($this->user->getIdUser());
		$averageTotalRating = round($totalRating/$seniority);
		$dateInscription = Outils_Date::getFrDateFromSQL($this->user->getTime(),false);
		$analyse = "<div class=\"statsanalysis\">"; 
		$analyse .= "<p>Sur cette période, vous avez évalué en moyenne <span class=\"ecbleu\">{$averageRating}</span> morceaux par {$averageRatingUnit}.</p>";
		$analyse .= "<p>Depuis votre inscription (le {$dateInscription}), vous évaluez en moyenne <span class=\"ecbleu\">{$averageTotalRating}</span> morceaux par jour.</p>";
		$analyse .= "</div>";
		
		return $chartImg.$analyse;
	}
	
	private function getStatsHistory($type,$limit){
		$today = strtotime(date('Y-m-d'));
		$thisWeek = date('W');
		$ratingByT = array();
		$result = array();
		switch($type){
			case DAY:
				$ratingByT = User_Bd::getHistoryStats($this->user->getIdUser(),DAY,$limit);
				$lastweekday = mktime(0, 0, 0, date("m"), date("d")-7,   date("Y"));
				for ($i=$lastweekday;$i<=$today;$i+=8400){
					$result[date(('Y-m-d'),$i)] = 0;
					foreach($ratingByT as $elt){
						if ( $elt['n_t']==date(('Y-m-d'),$i) ){
							$result[date(('Y-m-d'),$i)] = $elt['nb_rating'];
							break;	
						}
					}
				}	
				break;	
			
			case WEEK:
				$ratingByT =  User_Bd::getHistoryStats($this->user->getIdUser(),WEEK,$limit);
				for ($i=0;$i<$limit;$i++){
					$result[$i]['n_t'] = $thisWeek-$limit+1+$i;
					$result[$i]['nb_rating'] = 0;
					foreach($ratingByT as $elt){
						if ( $elt['n_t']==$thisWeek-$limit+1+$i){
							$result[$i]['n_t']== $elt['n_t'];
							$result[$i]['nb_rating'] = $elt['nb_rating'];
							break;	
						}
					}
					
				}		
				break;
				
			default:
				throw new Exception("$type non supporté");
		}
				//var_dump($ratingByT);
		return $result;
	}
	
	
	private function getSeniority(){
		$usertime = strtotime($this->user->getTime());	
		$today = strtotime(date('Y-m-d'));
		$seniority = round(($today - $usertime)/(60*60*24));
		return $seniority;
	}
	
	private function evalChart(){
		$alt = "Vos évaluations selon les scores attribués";
		$tabScores = User_Bd::getUserRatingByScore($this->user->getIdUser());
		$like = 0;
		$dislike = 0;
		$unrated = 0;
		$withoutopinion = 0;
		$totalEval = 0;
		foreach ($tabScores as $score){
			if ($score['score'] >5)
				$like += $score['nb'];	
			else {
				if ($score['score'] == -1)
					$unrated +=$score['nb'];
				else {
					if ($score['score'] <5)
						$dislike += $score['nb'];	
					else {
						if ($score['score']==5)
							$withoutopinion+=$score['nb'];
					}
				}
			}
			if ($score['score'] != -1)
				$totalEval+= $score['nb'];
		}
		
		if ($totalEval < 1){
			return "<p>Vous n'avez pas encore évalué un morceau pour l'instant</p>";
		}
		
		$likePercent = round($like*100/$totalEval);
		$dislikePercent = round($dislike*100/$totalEval);
		$chart="http://chart.apis.google.com/chart?chf=bg,s,E6E6E6&amp;chs=300x150&amp;cht=p&amp;chco=7EB7BF&amp;chd=t:{$like},{$dislike},{$withoutopinion}&amp;chdl=J'aime|Je+n'aime+pas|Neutre&amp;chp=0&amp;chco=7EB7BF|8A5050|BBBBBB";
		
		$chartImg = "<figure><figcaption>{$alt} :</figcaption> <img src=\"{$chart}\" alt=\"{$alt}\"/></figure> ";
		$analyse = "<div class=\"statsanalysis\">"; 
		$analyse .= "<p>Vous aimez <span class=\"ecbleu\">{$likePercent}%</span> des morceaux que vous évaluez.</p>";
		$analyse .= "</div>";
		
		return $chartImg.$analyse;
		
	}
	

	
	public function getAvatarImg($size="mini"){
		$image = Image_Bd::getImageByIdUser($this->user->getIdUser());
			switch($size){
				case "vignette":
					if (!$image)
						$method = ENTREPOT_URL . "defaultavatar.png";
					else
						$method = $image->getVignette();
					break;
				case "mini":
					if (!$image)
						$method = ENTREPOT_URL . "defaultminiavatar.png";
					else
						$method = $image->getMiniVignette();
					break;
				case "pico":
					if (!$image)
						$method = ENTREPOT_URL . "defaultpicoavatar.png";
					else
						$method = $image->getPicoVignette();
					break;
				default :
					if (!$image)
						$method = ENTREPOT_URL . "defaultminiavatar.png";
					else
						$method = $image->getMiniVignette();
					break;
			}
			$src = $method;
		
		return "<img class=\"avatar\" src=\"{$src}\" alt=\"Avatar de {$this->user->getName()}\" />";
		
	}
	
	private function getProfilAvatar(){
		$avatar = $this->getAvatarImg("vignette");
		$uploadForm = Image_Form::makeUploader("../ajax/ping.php?a=uploaderImage");
		$html ="<div class=\"avatarcolonne interactioncontainer\"><figure id=\"userprofilavatar\">{$avatar}</figure>{$uploadForm}";
		$html .= "<div class=\"interaction\"><a href=\"index.php?a=delAvatar\" class=\"supprAvatar\">suppr.</a> <a href=\"index.php?a=changeAvatar\" class=\"modifAvatar\">modif.</a></div></div>";
		
		return $html;
	}
	
	public function mesInfos(){
		$html = <<<EOT
		{$this->getProfilAvatar()}
		<div id="divinfosuser"><p>Nom : {$this->user->getName()}</p>
		<p>Adresse email : {$this->user->getMail()}</p>
		<p>Date de naissance : {$this->user->getBirthDate()}</p>
		</div>
		<div class="clearer"></div>
		
EOT;
			
		return $html;
	}
	
	private function getSocialInteraction(){
		$addFriendAction = "";
		if (! Friend_Bd::areFriends($_SESSION['infosAuth']->getIdUser(),$this->user->getIdUser())){
			$notification = Notification_Bd::getNotificationByRelation($_SESSION['infosAuth']->getIdUser(),$this->user->getIdUser(),DEMANDE_AJOUT_AMI);	
			if ( $notification !== false && $notification->getState()!=NOTIFICATION_DEL) // si notification DEL, c'est qu'ils étaient ami pendant un temps, a été supprimé et redemande à être ami
				$addFriendAction = "<span class=\"addFriendInteracState\">{$notification->getUserSubjectMsg()}</span>";
			else
				$addFriendAction = "<a href=\"#\" class=\"addfriendbutton authRequired\">ajouter à mes amis</a>";
		} else {
			$addFriendAction = "<span class=\"addFriendInteracState\">dans ma liste d'amis</span>";
		}
		$addWatchList = "";
		if (! Follower_Bd::AFollowB($_SESSION['infosAuth']->getIdUser(),$this->user->getIdUser())){
			$addWatchList =	"<a href=\"#\" class=\"addwatchlistbutton authRequired\">ajouter à ma watchlist</a>";		
		} else {
			$addWatchList= "<span class=\"addFollowerInteracState\">dans ma watch list</span>";
		}
		return $addFriendAction.$addWatchList;
		
	}
	
	public function getModerationInteraction(){
		$anc = "";
		$actanc = "";
		foreach ($GLOBALS['nomsDroitsUtilisateur'] as $k=>$v){
			if ($k >= $_SESSION['infosAuth']->getStatus()){
				
			} else {
				if ($this->user->getStatus() != $k){
					$anc .= "<a href=\"index.php?a=setStatus&amp;status={$k}\" class=\"setStatus\">{$v}</a>";
				} else {
					$anc .= "<span>{$v}</span>";
					$actanc = "<span>{$v}</span>";
				}
			}
		}
		
		$html = <<<EOT
			<div class="statusSwitcherContainer">
				{$actanc}
				<div class="switcher">
				{$anc}
				</div>
			</div>

EOT;
		
		return $html;	
	}
	
	public function getUserCard($moderate = false){
		if (!$moderate){
			$diagrammeVenn = isset($_SESSION['infosAuth']) && !empty ($_SESSION['infosAuth']) ? $this->getVennDiagram($_SESSION['infosAuth']->getIdUser(),JAIME,80,35) : "";
			$interac = isset($_SESSION['infosAuth']) && !empty ($_SESSION['infosAuth']) ? "<div class=\"socialinteraction\">".$this->getSocialInteraction()."</div>" : "";
		} else {
			$diagrammeVenn = "";
			if ($this->user->getStatus() < $_SESSION['infosAuth']->getStatus())
				$interac = "<div class=\"moderateinteraction\">".$this->getModerationInteraction()."</div>";
			else 
				$interac = "";
		}
		
		$html = <<<EOT
			<div class="usercard userL">
				<input type="hidden" class="idUser" value="{$this->user->getIdUser()}"/>
				<figure>{$this->getAvatarImg()}</figure>
				<div>
					<p><a href="#" class="username" title="Voir le profil de {$this->user->getName()}">{$this->user->getName()}</a></p>
					{$interac}
					<div class="affinitemusicalecard">
						{$diagrammeVenn}
					</div>
				</div>
				<div class="clearer"></div>
			</div>
EOT;
	return $html;
	}
	
	public function getVennDiagram($comparedTo_id_user,$scoreType,$long=200,$larg=100){
		switch($scoreType){
			case JAIME:
				$sc= " AND score >= 5";
				$scoreClause = " AND r1.score >= 5 AND r2.score >= 5";  
				$alt = "Diagramme de Venn représentant vos ressemblances avec {$this->user->getName()} concernant les morceaux que vous aimez";
				break;
			case JENAIMEPAS:
				$sc= " AND score <= 5";
				$scoreClause = " AND r1.score <= 5 AND r2.score <= 5";
				$alt = "Diagramme de Venn représentant vos ressemblances avec {$this->user->getName()} concernant les morceaux que vous n'aimez pas";
				break;
			default:
				$sc = "";
				$scoreClause = "";
				$alt = "Diagramme de Venn représentant vos ressemblances avec {$this->user->getName()} concernant les morceaux que vous avez noté";
				break;	
		}
		$tipstext = "L'intersection représente ce que <span>vous</span> aimez en commun avec {$this->user->getName()}";
		
		$nbIntersectScoreType = Rating_Bd::getNbCommonScore($comparedTo_id_user,$this->user->getIdUser(),$scoreClause);
		//$nbIntersectRating = Rating_Bd::getNbCommonScore($comparedTo_id_user,$this->user->getIdUser()," AND r1.score >= 0 AND r2.score >= 0");
		$nbThisUser = Rating_Bd::count("id_user={$this->user->getIdUser()}".$sc);
		$nbComparedToUser = Rating_Bd::count("id_user={$comparedTo_id_user}".$sc);
		$totUsers = $nbComparedToUser+$nbThisUser;
		$percentThisUser = $nbThisUser < 1 ? 0 : round($nbThisUser*100/$totUsers);
		$percentComparedToUser = $nbComparedToUser < 1 ? 0 : round($nbComparedToUser*100/$totUsers);
		// Le pourcentage pour l'intersection : le nombre qu'ils ont aimé / le nombre de truc noté par les 2
		$percentIntersect = $nbThisUser < 1 || $nbComparedToUser < 1  ? 0 : round(($nbIntersectScoreType*100)/($nbComparedToUser+$nbThisUser));
		
		$chart = "<figure>";
		$chart .= "<img class=\"venndiag\" title=\"Affinité Musicale :: {$tipstext}\" src=\"http://chart.apis.google.com/chart?chf=bg,s,E6E6E6&amp;chs={$long}x{$larg}&amp;cht=v&amp;chco=7EB7BF,808080&amp;chd=t:{$percentComparedToUser},{$percentThisUser},-1,{$percentIntersect},-1,-1,-1\" alt=\"{$alt}\" />";
		// légende : &amp;chdl=Moi|{$this->user->getName()}&amp;chdlp=l
		$chart .= "</figure>";
		$chart .="<span>{$percentIntersect}%</span>";
		
		return $chart;
	}
	
	public function getConcernedPageNotifications($type){
		$notificationsTab = Notification_Bd::getNotificationsByType($type,$this->user->getIdUser());
		if (sizeof($notificationsTab)==0)
			return null;
		$notificationTypeMsg = $notificationsTab[0]->getMessageTitle();
		$html = "<div class=\"notificationcontainer\"><p>{$notificationTypeMsg}</p><ul>";
		foreach ($notificationsTab as $notification){
			$html .="{$notification->getNotificationMsg()}";	
		}
		$html .= "</ul></div>";
		
		return $html;
		
	}
	
	public function getListNotifications(){
		
		$notifs = new Liste_Paginee("Notification_Bd", "getNotifications", "id_user_object={$this->user->getIdUser()} AND state=".NOTIFICATION_NEW." ORDER BY time DESC");
    	$notifsUi = new Liste_Paginee_Ui($notifs,10,7,true);
		$listNotifs = $notifs->count() > 0 ? "<ul>". $notifsUi->makeHtml("Notification_Ui", "getNotificationMsg",array(true)) ."</ul>" : "<p class=\"resultS\">Vous n'avez pas de nouvelles notifications</p>";
		
		return $listNotifs;
		
	}
	
	public function getEnBref(){
		$nbEval = Rating_Bd::count("score >=0 AND id_user={$this->user->getIdUser()}");
		$nbAmis = Friend_Bd::count("WHERE id_user1={$this->user->getIdUser()}");
		$nbAbonnes = Follower_Bd::count("id_user_object={$this->user->getIdUser()}");
		$nbAbonnements = Follower_Bd::count("id_user_subject={$this->user->getIdUser()}");
		
		$html= <<<EOT
			<p><strong>$nbEval</strong>	titres évalués</p>
			<p><strong>$nbAmis</strong>	amis</p>
			<p><strong>$nbAbonnes</strong> abonnés</p>
			<p><strong>$nbAbonnements</strong> abonnements</p>
EOT;

	return $html;
	}
	
	public function getMiniUserCardFromTitle($id_title=""){
		
		$avatar = $this->getAvatarImg("pico");
		
		if ($id_title !=""){
		
		$rating = Rating_Bd::getRating($this->user->getIdUser(),$id_title);
		$date = Outils_Date::relativeTime(strtotime($rating->getTime()));
		
		if ($rating->getScore() > 5)
			$rating = "<img src=\"../ui/images/aimemini.png\" alt=\"J'aime\"/>";
		else 
			if ($rating->getScore() == 5)
				$rating = "<img src=\"../ui/images/neutremini.png\" alt=\"Sans avis\"/>";
			else 
				if ($rating->getScore() >=0)
					$rating = "<img src=\"../ui/images/aimepasmini.png\" alt=\"J'aime pas\"/>";
				else 
					$rating ="?";
					
		} else {
			$rating="";
			$date="";
		}
		
		$html = <<<EOT
			<div class="titleusercard userL">
				<input type="hidden" class="idUser" value="{$this->user->getIdUser()}"/>
				<figure>{$avatar}</figure>
				<div>
					<span><a href="#" class="username" title="Voir le profil de {$this->user->getName()}">{$this->user->getName()}</a></span>
					<span class="titleusercard_rat">{$rating}</span>
					<span class="titleusercard_date">{$date}</span>
				</div>
				<div class="clearer"></div>
			</div>
EOT;

	return $html;
				
	}
	
	public function getMiniUserCardFriend(){
		return $this->getMiniUserCardFromTitle();	
	}
	
	
	public static function getEvalByTitle($id_title){
		$nbAime = Rating_Bd::count("score >5 AND id_title={$id_title}");
		$nbAimePas = Rating_Bd::count("score >=0 AND score < 5 AND id_title={$id_title}");
		$nbNeutre = Rating_Bd::count("score = 5 AND id_title={$id_title}");
		if ($nbAime+$nbAimePas+$nbNeutre ==0){
			$html= <<<EOT
				<p>Soyez le premier à évaluer ce titre</p>		
EOT;
		} else {
			$html = <<<EOT
			<ul>
				<li class="aimeEvalByTitle">{$nbAime}</li>
				<li class="aimePasEvalByTitle">{$nbAimePas}</li>
				<li class="neutreEvalByTitle">{$nbNeutre}</li>
			</ul>
			<div class="clearer"></div>
EOT;
		}
			return $html;
		
	}
	
	public function getProfilUserCard(){
		$interac = isset($_SESSION['infosAuth']) && !empty ($_SESSION['infosAuth']) ? "<div class=\"socialinteraction\">".$this->getSocialInteraction()."</div>" : "";
		$dateInsc = "<p>{$this->user->getName()} est inscrit depuis le ".Outils_Date::getFrDateFromSQL($this->user->getTime(),false)."</p>";
		$html = <<<EOT
			<div class="usercard userL">
				<input type="hidden" class="idUser" value="{$this->user->getIdUser()}"/>
				<figure>{$this->getAvatarImg()}</figure>
				<div class="itcont">
					{$interac}
				</div>
				<div class="clearer"></div>
								{$dateInsc}
			</div>
EOT;
		return $html;
	}

}

?>